import React, { useState } from 'react';
import mammoth from 'mammoth';
import { diffWords } from 'diff';

const DocxComparison = () => {
  const [file1, setFile1] = useState(null);
  const [file2, setFile2] = useState(null);
  const [htmlPreview1, setHtmlPreview1] = useState('');
  const [htmlPreview2, setHtmlPreview2] = useState('');
  const [diffResult, setDiffResult] = useState('');

  // 处理文件选择
  const handleFileChange = (e, setFile) => {
    const file = e.target.files[0];
    setFile(file);
  };

  // 读取文件内容
  const readFile = (file) => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = (event) => resolve(event.target.result);
      reader.onerror = (error) => reject(error);
      reader.readAsArrayBuffer(file);
    });
  };

  // 将 .docx 转换为 HTML 保留样式
  const convertToHtmlWithStyles = (file) => {
    return readFile(file)
      .then((arrayBuffer) =>
        mammoth.convertToHtml({ arrayBuffer, styleMap: [
          "p => p", // 保留段落样式
          "h1 => h1", // 保留标题样式
          "b => b", // 加粗
          "i => i", // 斜体
          "u => u", // 下划线
        ] })
      )
      .then((result) => result.value);
  };

  // 比较文件差异
  const compareDocs = async () => {
    if (!file1 || !file2) return;

    try {
      // 转换文件为 HTML 内容，保留样式
      const html1 = await convertToHtmlWithStyles(file1);
      const html2 = await convertToHtmlWithStyles(file2);

      setHtmlPreview1(html1);
      setHtmlPreview2(html2);

      // 转换为纯文本以进行差异比较
      const text1 = await convertToText(file1);
      const text2 = await convertToText(file2);

      // 使用 diffWords 对比文本，找出差异
      const diff = diffWords(text1, text2);

      // 格式化输出差异，标记插入和删除的部分
      const formattedDiff = diff
        .map((part) =>
          part.added
            ? `<span style="background-color: #d4f7d4;">${part.value}</span>` // 插入部分
            : part.removed
            ? `<span style="background-color: #fddcdc; text-decoration: line-through;">${part.value}</span>` // 删除部分
            : part.value
        )
        .join('');

      setDiffResult(formattedDiff);
    } catch (error) {
      console.error('Error comparing files:', error);
    }
  };

  // 将 .docx 转换为纯文本（用于差异比较）
  const convertToText = (file) => {
    return readFile(file)
      .then((arrayBuffer) => mammoth.extractRawText({ arrayBuffer }))
      .then((result) => result.value);
  };

  return (
    <div>
      <h2>Docx Comparison</h2>
      <div>
        <input type="file" onChange={(e) => handleFileChange(e, setFile1)} />
        <input type="file" onChange={(e) => handleFileChange(e, setFile2)} />
        <button onClick={compareDocs}>Compare</button>
      </div>

      <div style={{ display: 'flex', marginTop: '20px' }}>
        <div style={{ width: '45%', marginRight: '10px' }}>
          <h3>File 1 Preview</h3>
          <div
            dangerouslySetInnerHTML={{
              __html: htmlPreview1,
            }}
          />
        </div>
        <div style={{ width: '45%' }}>
          <h3>File 2 Preview</h3>
          <div
            dangerouslySetInnerHTML={{
              __html: htmlPreview2,
            }}
          />
        </div>
      </div>

      <div style={{ marginTop: '20px' }}>
        <h3>Diff Result (Textual)</h3>
        <div
          dangerouslySetInnerHTML={{
            __html: diffResult,
          }}
        />
      </div>
    </div>
  );
};

export default DocxComparison;
